package com.wellink.demo1;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class MyAdapter extends BaseAdapter {

    private Context context;
    private List<DataItem> itemList;

    public MyAdapter(Context context, List<DataItem> itemList) {
        this.context = context;
        this.itemList = itemList;
    }

    @Override
    public int getCount() {
        return itemList.size();
    }

    @Override
    public DataItem getItem(int position) {
        return itemList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(null == convertView){
            LayoutInflater inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(R.layout.item_layout,null);
            holder = new ViewHolder();
            holder.icon = convertView.findViewById(R.id.icon);
            holder.text = convertView.findViewById(R.id.text);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        DataItem item = itemList.get(position);
        if(null != item){
            holder.icon.setImageResource(item.getId());
            holder.text.setText(item.getContent());
        }


        return convertView;
    }

    public void add(int pos,DataItem item){
        itemList.add(pos,item);
        notifyDataSetChanged();
    }

    public void update(List<DataItem> itemList){
        this.itemList.clear();
        this.itemList.addAll(itemList);
        notifyDataSetChanged();
    }

    public void update(int pos,DataItem item){
        if(pos < itemList.size()){
            this.itemList.set(pos,item);
        }

        notifyDataSetChanged();
    }

    public void remove(int pos){
        if(pos < this.itemList.size()){
            this.itemList.remove(pos);
        }
        notifyDataSetChanged();
    }

    public void clear(){
        this.itemList.clear();
        notifyDataSetChanged();
    }
}


class ViewHolder{
    ImageView icon;
    TextView text;
}
